<template>
  <el-dialog
    v-dialogDrag
    :visible="isDialogVisible"
    center
    width="80%"
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="closeEdit"
  >
    <dialogHeader slot="title" :title="titleName" :style-type="$store.state.app.dialogType" />
    <one-table-template
      ref="multipleTable"
      :dynamic-api-config="apiConfig"
      :dynamic-buttons="dynamicButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="dynamicTableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :callback-obj="callbackObj"
      :dynamic-export-converts="dynamicExportConverts"
      :refresh-table-key="refreshTableKey"
    />
  </el-dialog>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  mixins: [oneTableWithViewTemplateMixins],
  props: {
    isDialogVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: String,
      default: ''
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      titleName: '添加城市仓库',
      refreshTableKey: '0',
      // 网格查询API配置对象
      apiConfig: {
        ServiceCode: 'findAllCity',
        APIUrl: '/mp/e3sh/vesale/basics/regionalCityWMService/findAllCity.do'
      },
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '城市仓库名称：',
              codeField: 'carHouseName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey2',
              labelName: '城市仓库编码：',
              codeField: 'carHouseCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            }
          ],
      // form 的表单对象
      formField: this.$utils.getFormField(
        this,
        {
          carHouseName: '',
          carHouseCode: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      // 动态组件-按钮
      dynamicButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'search',
              clickEvent: () => this.queryTable(1),
              text: '查询'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              icon: 'iconfont  icon-cancel',
              clickEvent: () => this.reset(),
              text: '重置',
              name: 'reset'
            },
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'add',
              disabled: true,
              clickEvent: () => this.add(),
              text: '添加',
              position: 'left'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              icon: 'iconfont  icon-cancel',
              clickEvent: () => this.closeEdit(),
              text: '取消',
              position: 'left'
            }
          ],
      // 动态组件-表格网格列
      dynamicTableCols:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols : [
            {
              prop: 'carStockHouseId',
              label: '城市仓库ID',
              hidden: true
            },
            {
              prop: 'provinceName',
              label: '省份'
            },
            {
              prop: 'cityName',
              label: '城市'
            },
            {
              prop: 'countyName',
              label: '区县'
            },
            {
              prop: 'carHouseCode',
              label: '城市仓库编码'
            },
            {
              prop: 'carHouseName',
              label: '城市仓库名称'
            },
            {
              prop: 'carHouseAddr',
              label: '详细地址'
            },
            {
              prop: 'carHouseManager',
              label: '管理员'
            },
            {
              prop: 'carHouseTEL',
              label: '电话'
            },
            {
              prop: 'isDefaultAddr',
              label: '是否默认搬入'
            },
            {
              prop: 'isEnableCode',
              label: '启用状态'
            },
            {
              prop: 'REMARK',
              label: '备注'
            }
          ],
      // 字段格式化转换（用于导出excel）（kvs表示键值转换）
      dynamicExportConverts: {
        isEnable: {
          convert: 'kvs',
          kvs: {
            '1': '是',
            '0': '否'
          }
        }
      },
      selectList: '',
      infoList: [],
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.infoList = selection
          var arr = selection.map(t => t.carStockHouseId)
          var str = arr.join(',')
          this.selectList = str
          // console.log(str)
          this.handleSelectionChange(selection)
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.queryTable(1)
    })
    this.initData()
  },
  methods: {
    handleSelectionChange(selection) {
      const btns = this.dynamicButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },
    add() {
      const that = this
      const queryObj = {
        // api配置
        apiConfig: { ServiceCode: 'regionalCity', APIUrl: '/mp/e3sh/vesale/basics/regionalCityWMService/regionalCity.do' },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          pageSize: '',
          pageIndex: '',
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: { infoList: this.infoList, areaStockId: this.dataForForm }
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then(response => {
        if (response.msg) {
          this.$message({
            message: response.msg,
            type: 'warn',
            uration: 2000
          })
        }
        this.closeEdit(1)
        this.$emit('querymenue')
        this.$emit('areackQuery')
      })
    },
    // form表单组件每个元素所占栅格栏数每行24格
    spanNum() {
      return 24
    },

    // 关闭弹窗
    closeEdit(type) {
      this.$emit('close', type)
    },

    // 表单数据初始化
    initData() {
      // if (JSON.stringify(this.dataForForm) === '{}') {
      //   this.titleName = '新增'
      //   this.dynamicFieldsData.senceCode = 'Ｘ'
      //   return
      // } else {
      //   this.titleName = '修改'
      //   this.dynamicFieldsData.id = this.dataForForm.id
      //   this.dynamicFieldsData.updateControlId = this.dataForForm.updateControlId
      //   this.dynamicFormFields.forEach((item) => {
      //     if (item.label === '接口编码') {
      //       item.disabled = true
      //     }
      //   })
      //   this.queryById()
      // }
    },

    // 编辑表单详情数据查询
    queryById() {
    //   const that = this
    //   const saveObj = { id: this.dataForForm.id }
    //   const apiQueryRow = ['apiCode', 'apiName']
    //   that.$utils.apiRrequest(that, 'mutation', testApis.dbSenceApiQueryFindObjectById, saveObj, (data) => {
    //     if (data) {
    //       const resultData = data.data[testApis.dbSenceApiQueryFindObjectById.ServiceCode].rows
    //       setDynamicFieldsData(this.dynamicFieldsData, resultData)
    //     }
    //   }, apiQueryRow)
    },

    // 保存
    save() {
    //   const that = this
    //   this.$refs['multipleForm'].$children[0].validate(valid => {
    //     if (valid) {
    //       that.$utils.apiRrequest(that, 'mutation', testApis.dbSenceApiMutationSaveObject, this.dynamicFieldsData, (data) => {
    //         if (data) {
    //           that.$message({
    //             message: '保存成功',
    //             type: 'success',
    //             duration: 2000
    //           })
    //           this.closeEdit(1)
    //         }
    //       })
    //     }
    //   })
    }

    // 重置
    // resetData() {
    //   const that = this
    //   this.dynamicFormFields.forEach((e, i) => {
    //     that.dynamicFieldsData[e.codeField] = ''
    //   })
    //   if (JSON.stringify(this.dataForForm) !== '{}') {
    //     this.dynamicFieldsData.apiCode = this.dataForForm.apiCode
    //   }
    //   this.$refs['multipleForm'].$children[0].clearValidate()
    // }
  }
}
</script>

